<template>
  <a-modal 
    :get-container="getContainer" 
    :visible="visible" 
    :width="850" 
    :confirmLoading="loading" 
    @ok="handleSubmit"
    @cancel="() => {
      resetFields();
      $emit('cancel');
    }" 
    centered>
    
    <!-- header -->
    <a-divider orientation="left">
      <b>新增${view.entityComment}</b>
    </a-divider>
    
    <!-- form -->
    <a-spin :spinning="loading">
      <a-form name="model-form" layout="horizontal" :model="entityRef" :rules="rulesRef" :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-row type="flex" justify="start">
<#list view.propertyList as property>
	<#if (!property.isPrimaryKey() 
	&& property.isInsertable()
	&& property.propertyName != "id" 
	&& property.propertyName != "vcid"
	&& property.propertyName != "createDate"
	&& property.propertyName != "createOperatorId"
	&& property.propertyName != "lastUpdateDate"
	&& property.propertyName != "lastUpdateOperatorId"
	&& property.propertyName != "modifyAble"
	&& property.propertyName != "modifiable"
	&& property.propertyName != "valid")>
		<#if property.isSimpleValueType()>
          <a-col :xs="24" :sm="24" :md="12" :lg="12">
            <a-form-item label="${property.propertyComment}" name="${property.columnName}">
			<#if (property.propertyName == "parentId")>
              <a-tree-select
                :allowClear="true"
                v-model:value="entityRef.parentId" 
                placeholder="请选择上级${view.entityComment}" 
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="${view.entityTypeSimpleName?uncap_first}TreeData" 
                :treeDefaultExpandAll="true" 
                :field-names="{
                  label: 'name', 
                  value: 'id' 
                }"/>
			<#elseif property.propertyTypeSimpleName == 'boolean' || property.propertyTypeSimpleName == 'Boolean'>
              <a-radio-group
                v-model:value="entityRef.${property.propertyName}"
                name="radioGroup"
                :options="[
                  { label: '是', value: true },
                  { label: '否', value: false },
                ]"
              />
			<#elseif property.isBasicdataEnum()>
              <a-select
                v-model:value="entityRef.${property.propertyName}"
                placeholder="请选择${property.propertyComment}"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :options="${property.propertyName}Options"
                />
			<#elseif  property.propertyTypeSimpleName == 'Date'>
              <a-date-picker v-model:value="entityRef.${property.propertyName}" value-format="YYYY-MM-DD" style="width:100%" :placeholder="''"/>
			<#else>
              <a-input v-model:value="entityRef.${property.propertyName}" />
			</#if>
            </a-form-item>
          </a-col>
        <#else>
        	<#if property.isBasicdataType()>
          <a-col :xs="24" :sm="24" :md="12" :lg="12">
            <a-form-item label="${property.propertyComment}" name="${property.columnPropertyName}">
              <a-select
                v-model:value="entityRef['${property.columnPropertyName}']"
                placeholder="请选择${property.propertyComment}"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :options="${property.propertyName}Options"
                />
            </a-form-item>
          </a-col>
        	</#if>
		</#if>
	</#if>
</#list>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts">
import type { PropType } from 'vue';
import {defineComponent, reactive, ref, toRaw, watch} from 'vue';
import {Form} from 'ant-design-vue';
import {queryList as queryEnumList} from '@/api/basicdata/basic_data_enum';
import {queryList as queryBasicDataList} from '@/api/basicdata/basic_data';
import {addHandlerWrap, toTreeList, validatorRemoteValidateWrap} from '@/utils/commons';
import {add, exists, queryList} from '@/api/';
import type { RuleObject } from 'ant-design-vue/lib/form';
<#if view.parentProperty?? || view.parentIdProperty?? || view.isHasBasicDataProperty() || view.isHasBasicDataEnumProperty()>
import type { <#if view.parentProperty?? || view.parentIdProperty??>TreeSelectProps</#if><#if view.isHasBasicDataProperty() && view.isHasBasicDataEnumProperty()><#if view.parentProperty?? || view.parentIdProperty??> ,</#if>SelectProps</#if> } from 'ant-design-vue';
</#if>

<#if view.isHasBasicDataEnumProperty()>
</#if>
<#if view.isHasBasicDataProperty()>
</#if>
import type { ${view.entityTypeSimpleName} } from '@/api/${packageName}/${view.entityTypeSimpleName?replace("([a-z])([A-Z]+)","$1_$2","r")?lower_case}';

const formLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
    md: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
    md: { span: 20 },
  },
};
export interface AddParams {
<#if view.parentProperty?? || view.parentIdProperty??>
    parentId: string,
</#if>
    [key:string]: any,
}
export const pageContextProps = {
    getContainer: {
        type: Function as PropType<() => HTMLElement>,
        default: () => null,
    },
    visible: {
        type: Boolean,
        required: true,
    },
    params: {
        type: Object as PropType<AddParams>,
        default: () => null,
    },
};

export default defineComponent({
  name: 'Add${view.entityTypeSimpleName}',
  props: { ...pageContextProps },
  emits: ['ok', 'cancel'],
  setup(props, { emit }) {
<#list view.propertyList as property>
    <#if property.isBasicdataEnum()>
    const ${property.propertyName}Options = ref<SelectProps['options']>([]);
    queryEnumList('${property.propertyTypeSimpleName}').then((rows) => {
      rows.forEach((d) => {
        ${property.propertyName}Options.value.push({
          label: d.name,
          value: d.key,
        });
      });
    });
    </#if>
    <#if property.isBasicdataType()>
    const ${property.propertyName}Options = ref<SelectProps['options']>([]);
    queryBasicDataList('${property.propertyTypeSimpleName}').then((rows) => {
      rows.forEach((d) => {
        ${property.propertyName}Options.value.push({
          label: d.name,
          value: d.id,
        });
      });
    });
    </#if>
</#list>
<#if view.parentProperty?? || view.parentIdProperty??>
    //加载上级组织机构树型列表
    const ${view.entityTypeSimpleName?uncap_first}TreeData = ref<TreeSelectProps['treeData']>([]);
</#if>

    const loading = ref(false);
    //定制逻辑：初始化数据结构
    const initValues = () => ({
<#list view.propertyList as property>
	<#if (!property.isPrimaryKey() 
	&& property.isInsertable()
	&& property.propertyName != "id" 
	&& property.propertyName != "vcid"
	&& property.propertyName != "createDate"
	&& property.propertyName != "createOperatorId"
	&& property.propertyName != "lastUpdateDate"
	&& property.propertyName != "lastUpdateOperatorId"
	&& property.propertyName != "modifyAble"
	&& property.propertyName != "modifiable"
	&& property.propertyName != "valid")>
		<#if property.isSimpleValueType()>
            <#if property.propertyTypeSimpleName == 'boolean'>
      ${property.propertyName}: false,
  			<#elseif property.propertyTypeSimpleName == 'Boolean'>
      ${property.propertyName}: '',
            <#elseif property.isEnum()>
      ${property.propertyName}: '',
            <#elseif  property.propertyTypeSimpleName == 'Date'>
      ${property.propertyName}: '',
            <#elseif  property.propertyTypeSimpleName == 'int'
            	|| property.propertyTypeSimpleName == 'long'
                || property.propertyTypeSimpleName == 'double'
                || property.propertyTypeSimpleName == 'float'>
      ${property.propertyName}: 0,
  			<#elseif  property.propertyTypeSimpleName == 'Intengrt'
  				|| property.propertyTypeSimpleName == 'Long'
                || property.propertyTypeSimpleName == 'BigDecimal'
                || property.propertyTypeSimpleName == 'Double'
                || property.propertyTypeSimpleName == 'Float'>
      ${property.propertyName}: '',
  			<#elseif  property.isEnum()>
      ${property.propertyName}: '',
            <#else>
      ${property.propertyName}: '',
            </#if>
		</#if>
	<#else>
        	<#if property.isBasicdataType()>
      '${property.columnPropertyName}': '',
        	</#if>	
	</#if>
</#list>
    } as ${view.entityTypeSimpleName});
        
    const entityRef = reactive<${view.entityTypeSimpleName}>(initValues());
    const rulesRef = reactive({
            //注意如果数据类型不相同，一定要指定数据类型 `type` 否则会校验失败
<#if view.codeProperty??>
      //注意如果数据类型不相同，一定要指定数据类型 `type` 否则会校验失败
      code: [{ message: '编码不能为空', required: true, trigger: 'blur' },
        { message: '编码已经存在', validator: validatorRemoteValidateWrap(( value: any ) => {
          const params = {};
          params['code'] = value;
          return exists(params);
        }),
        trigger: 'blur',
       },
      ],
</#if>
<#if view.nameProperty??>
      name: [{ message: '名称不能为空', required: true, trigger: 'blur' }],
</#if>
    } as { [key: string]: Array<RuleObject> });
    
    const { resetFields, validate } = Form.useForm(entityRef, rulesRef);
    const addHandler = addHandlerWrap(add, '${view.entityComment}', props.getContainer);
    const handleSubmit = (e: Event) => {
      e.preventDefault();
      if (loading.value) {
        return;
      }
      loading.value = true;
      validate().then(() => {
        const data = toRaw(entityRef);
        //console.log(data);
        addHandler(data, data.name).then(res => {
          loading.value = false;
          emit('ok', res);
          resetFields();
        }).catch(errorMessage => {
          loading.value = false;
          console.log('error', errorMessage);
        });
      }).catch(err => {
        console.log('error', err);
        loading.value = false;
      });
    };

    //当页面被打开的时候调用逻辑
    //监听入参变化，当父组件传入参数动态变化后，子组件需响应变化
    watch(props, newVal => {
      if (newVal.visible) {
        onLoadSuccess();
      }
    });
    const onLoadSuccess = () => {
<#if view.parentProperty?? || view.parentIdProperty??>
      queryList({ <#if view.validProperty??>valid: true</#if> }).then(rows => {
        ${view.entityTypeSimpleName?uncap_first}TreeData.value = [...toTreeList(rows)];
      });
      //设置父级id
      entityRef.parentId = props.params.parentId;
</#if>
    };
    return {
      ...formLayout,
      
      loading,
      entityRef,
      rulesRef,
      resetFields,
      handleSubmit,
      
<#if view.parentProperty?? || view.parentIdProperty??>
      ${view.entityTypeSimpleName?uncap_first}TreeData,
</#if>
<#list view.propertyList as property>
    <#if property.isBasicdataEnum()>
      ${property.propertyName}Options,
    </#if>
    <#if property.isBasicdataType()>
      ${property.propertyName}Options,
    </#if>
</#list>
    };
  },
  components: {},
});
</script>